//
//  SerialPostDateView.m
//  XPhoto
//
//  Created by sentinel on 2020/4/10.
//  Copyright © 2020 baboy. All rights reserved.
//

#import "SerialPostDateView.h"
#import <BKKIt/NSThread+x.h>
#import <BKKIt/BKDropMenu.h>
#import "UIScrollView+x.h"

@interface SerialPostDateView()<UIScrollViewDelegate, BKDropMenuDelegate>
@property(nonatomic, assign) CGFloat navBarHeight;
@property(nonatomic, assign) CGFloat serialGroupViewOriginOffsetY;
@end
@implementation SerialPostDateView
- (void)removeTableViewObserve{
    [self.tableView removeObserver:self forKeyPath:@"contentSize"];
}
- (void)dealloc{
    [self removeTableViewObserve];
}
- (void)initAfterAwakeFromNib{
    [self.tableView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
}
- (void)awakeFromNib{
    [super awakeFromNib];
    [self initAfterAwakeFromNib];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if(object == self.tableView && [keyPath isEqualToString:@"contentSize"]){
        [self tableViewContentSizeChanged];
    }
}
- (void)tableViewContentSizeChanged{
    CGRect frame = self.contentScrollView.frame;
    CGFloat h = MAX(self.tableView.contentSize.height, self.bounds.size.height - frame.origin.y);
    h = MIN(self.bounds.size.height - self.navBarHeight - self.serialGroupView.bounds.size.height, self.tableView.contentSize.height);
    if (h > frame.size.height) {
        DLOG(@"%f,%f,%@,%@", frame.size.height,h, NSStringFromUIEdgeInsets(self.safeAreaInsets),NSStringFromUIEdgeInsets(self.superview.safeAreaInsets));
        frame.size.height = h;
        self.contentScrollView.frame = frame;
        self.contentSize = CGSizeMake(self.bounds.size.width, frame.origin.y + h);
    }
}
- (CGFloat)navBarHeight{
    CGFloat h = self.navBar.bounds.size.height - self.superview.safeAreaInsets.top;
    return h;
}
- (CGFloat)serialGroupViewOriginOffsetY{
    CGFloat offsetY = self.contentScrollView.frame.origin.y - self.serialGroupView.frame.size.height;
    return offsetY;
}
- (void)reload{
    [self layoutSerialGroupView];
    self.tableView.tableFooterView = [UIView new];
    SysDictItem *dictItem = [SysDict itemForValue:[@(SERIAL_TYPE_DATE) description] dictKey:SYS_DICT_SERIAL_TYPE_KEY];
    self.serialGroupView.title = dictItem?dictItem.title:nil;
    self.serialGroupView.selectedIndex = 0;
    [self search:0];
}
#pragma Http Loading
- (void)search:(NSInteger)offset{
    PostSearchArgs *args = [PostSearchArgs new];
    args.serialId = [NSNumber numberWithLong:self.postSerial.id];
    args.offset = offset;
    args.pageSize = 100;
    [Post searchBySerialWithArgs:args
                callback:^(id  task, id  photos, NSError * _Nonnull error) {
        if (error) {
            [BKIndicator showMessage:error.localizedDescription duration:3.0f completion:nil];
            return;
        }
        if (offset == 0) {
            self.posts = [NSMutableArray array];
        }
        [self.posts addObjectsFromArray:photos];
        [self addPosts:photos];
        BOOL loadMore = args.pageSize == [photos count];
        self.tableView.loadMore = loadMore;
        self.serialGroupView.loadMore = loadMore;
        [self.tableView stopRefreshing];
        [self.tableView stopLoading];
        
        
    }];
}


- (void)addPosts:(NSArray*)posts{
    NSMutableArray *grps = [Post dateSerialGroup:self.groups withPhotoRecords:posts];
    self.groups = grps;
    self.serialGroupView.items = grps;
    self.photoMapView.items = self.posts;
    [self.tableView reloadData];
}
- (void)scrollViewWillBeginLoadingMore:(UIScrollView *)scrollView{
    [self search:self.posts.count];
}
#pragma BKTableView Delegate
- (PhotoTableViewCell *)photoTableViewCell{
    PhotoTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier: PHOTO_TABLE_VIEW_CELL_REUSE_ID];
    if (!cell) {
        cell = loadViewFromNib([PhotoTableViewCell class], self);
        cell.delegate = self.actionDelegate;
    }
    return cell;
}
- (Post *)postAtIndexPath:(NSIndexPath *)indexPath{
    Group *grp = [self.groups objectAtIndex:indexPath.section];
    Post *post = [grp.data objectAtIndex:indexPath.row];
    return post;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.groups.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    Group *grp = [self.groups objectAtIndex:section];
    NSInteger n = grp.data.count;
    return n;
}
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    PhotoTableViewCell *cachedCell = [self photoTableViewCell];
//    Post *post = [self postAtIndexPath:indexPath];
//    
//    CGFloat h = [cachedCell cellHeightWithPost:post width:self.tableView.bounds.size.width];
//    return h;
//}
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    return [self.serialGroupView height];
//}
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//    return self.serialGroupView;
//}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 490;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    Post *post = [self postAtIndexPath:indexPath];
    
    PhotoTableViewCell *cell = [self photoTableViewCell];
    cell.post = post;
    return cell;
}
/*
 *
 */
- (void)layoutSerialGroupView{
    CGRect frame = self.serialGroupView.frame;
    frame.origin.y = MAX(self.contentOffset.y+[self navBarHeight], self.serialGroupViewOriginOffsetY);
    self.serialGroupView.frame = frame;
    
    CGFloat alpha = 1- (frame.origin.y - self.contentOffset.y - self.navBarHeight)/self.navBarHeight;
    alpha = MIN(alpha, 0.98);
    self.navBar.alpha = alpha;
}
#pragma UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (scrollView == self.tableView) {
        CGFloat thresholdHeight = self.serialGroupViewOriginOffsetY - self.navBarHeight;
        //在阈值以内，滚动子tableView需要转化到父view的滚动

        CGFloat superOffsetY = MIN( scrollView.contentOffset.y + self.contentOffset.y, thresholdHeight);
        CGFloat subOffsetY = scrollView.contentOffset.y + self.contentOffset.y - superOffsetY;
        DLOG(@"=======%f,%f,%f", superOffsetY, subOffsetY, scrollView.contentOffset.y);
        [self setContentOffset:CGPointMake(0, superOffsetY)];
        if(subOffsetY != scrollView.contentOffset.y){
            [scrollView setContentOffset:CGPointMake(0, subOffsetY)];
        }
        [scrollView scrollViewDidScroll];
    }
    [self layoutSerialGroupView];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    DLOG(@"scrollViewDidEndDragging:%@", NSStringFromCGPoint(scrollView.contentOffset));
    //处理因子视图向下拖拽而导致父视图无法回到原位置
    if (scrollView == self.tableView) {
        CGFloat offsetY = self.contentOffset.y;
        if (offsetY < 0) {
            [self setContentOffset:CGPointZero animated:YES];
        }
        CGFloat h = (self.contentSize.height - self.bounds.size.height);
        h = MAX(h, 0);
        if (self.contentOffset.y > h) {
            [self setContentOffset:CGPointMake(0, h) animated:YES];
        }
        [scrollView scrollViewDidEndDragging];
    }
}

- (void)didClickedSerialGroupItemAtIndex:(NSInteger)index{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:index];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
- (void)didClickedSerialGroupTitleButton:(UIButton *)button{
    if (self.actionDelegate && [self.actionDelegate respondsToSelector:@selector(didClickedSerialGroupTitleButton:)]) {
        [self.actionDelegate didClickedSerialGroupTitleButton:button];
    }
}
- (void)didClickedSerialGroupLoadingMoreButton:(UIButton *)button{
    [self.tableView setContentOffset:CGPointMake(0,self.tableView.contentSize.height - self.serialGroupViewOriginOffsetY + 60) animated:YES];
    [self.tableView startLoading];
}
- (void)dropMenu:(BKDropMenu *)dropMenu didSelectItem:(BKDropMenuItem *)item{
    DLOG(@"%@", item);
    if (self.actionDelegate && [self.actionDelegate respondsToSelector:@selector(dropMenu:didSelectItem:)]) {
        [self.actionDelegate dropMenu:dropMenu didSelectItem:item];
    }
}
+ (SerialPostDateView *)view{
    SerialPostDateView *view = loadViewFromNib([self class], nil);
//    view.layer.borderColor = [UIColor blueColor].CGColor;
//    view.layer.borderWidth = 5;
////
//    view.contentScrollView.layer.borderColor = [UIColor greenColor].CGColor;
//    view.contentScrollView.layer.borderWidth = 15;
//
    return view;
}

@end
